<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { debounce } from '@/utils/common'

const props = defineProps({
  width: {
    type: Number,
    default: 1920
  },
  height: {
    type: Number,
    default: 1080
  },
  delay: {
    type: Number,
    default: 500
  }
})

const scale = ref(0)
const scaleBoxRef = ref(null)

// 计算当前窗口的缩放比例
const getScale = () => {
  const { width, height } = props
  const wh = window.innerHeight / height
  const ww = window.innerWidth / width
  return ww < wh ? ww : wh
}

// 设置缩放比例
const setScale = () => {
  scale.value = getScale()
}

const debouncedSetScale = debounce(setScale, props.delay)

// 初始化
onMounted(() => {
  setScale()
  window.addEventListener('resize', debouncedSetScale)
})

// 清理事件监听器
onBeforeUnmount(() => {
  window.removeEventListener('resize', debouncedSetScale)
})
</script>

<template>
  <div
    class="scale-box"
    ref="scaleBoxRef"
    :style="{
      width: `${width}px`,
      height: `${height}px`,
      '--scale': scale,
    }"
  >
    <slot></slot>
  </div>
</template>

<style scoped>
.scale-box {
  position: absolute;
  transform: scale(var(--scale)) translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  transform-origin: 0 0;
  left: 50%;
  top: 50%;
  transition: 0.3s;
  z-index: 999;
}
</style>